package com.moorecat.app;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.moorecat.MooerApplication;
import com.moorecat.R;
import com.moorecat.bean.Shop;
import com.moorecat.http.HttpUtils;
import com.moorecat.utils.ui.UiUtils;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-12 上午07:49:38 类说明
 */
public class BusinessInfo extends Activity implements OnClickListener {

	private static final String TAG = "BusinessInfo";

	private ImageView call, checkMap, signin, star, concern, icon;

	private TextView businessName, zifei, rigion, type, phone, address,
			concernNum;

	private Shop businessInfo;

	private MooerApplication mooerApp;

	private int concernNumber;

	private ListView couponView, promotionView;

	private ScrollView infoScroll;

	private boolean concerning;

    private boolean isConcerning;

    private boolean downloading=false;

    public boolean isDownloading() {
        return downloading;
    }

    public void setDownloading(boolean downloading) {
        this.downloading = downloading;
    }

    @Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.business_info);
		mooerApp = (MooerApplication) getApplication();
		Intent intent = getIntent();
		businessInfo = (Shop) intent.getSerializableExtra("businessInfo");
		couponView = (ListView) findViewById(R.id.youhuiquan);
		promotionView = (ListView) findViewById(R.id.promotioninfo);
		icon = (ImageView) findViewById(R.id.business_icon);
		call = (ImageView) findViewById(R.id.call);
		checkMap = (ImageView) findViewById(R.id.check_map);
		signin = (ImageView) findViewById(R.id.signin);
		star = (ImageView) findViewById(R.id.star);
		concern = (ImageView) findViewById(R.id.concern);
		concernNum = (TextView) findViewById(R.id.concern_num);
		businessName = (TextView) findViewById(R.id.business_name);
		zifei = (TextView) findViewById(R.id.zifei);
		type = (TextView) findViewById(R.id.type);
		rigion = (TextView) findViewById(R.id.rigion);
		phone = (TextView) findViewById(R.id.phone);
		address = (TextView) findViewById(R.id.address);
		infoScroll = (ScrollView) findViewById(R.id.info_scroll);

		businessName.setText(businessInfo.getName());
		zifei.setText(getString(R.string.zifei_avg,
				businessInfo.getAvgConsumption()));
		type.setText(businessInfo.getCategoryName());
		rigion.setText(businessInfo.getAddress().getAreaName());
		concernNum.setText(getString(R.string.concern_num, businessInfo.getConcernNum()));
		phone.setText("电话："
				+ (businessInfo.getPhone() == null ? "" : businessInfo
						.getPhone()));
		address.setText("地址："
				+ (businessInfo.getAddress().getAddress1() == null ? ""
						: businessInfo.getAddress().getAddress1()));
		icon.setBackgroundResource(R.drawable.m_seller_pic_d);
		star.setBackgroundDrawable(UiUtils.selectStar(getResources(),
				businessInfo.getRating()));
		call.setOnClickListener(this);
		checkMap.setOnClickListener(this);
		signin.setOnClickListener(this);
		concern.setOnClickListener(this);
        if(mooerApp.isLoggedin()){
            boolean isFollow = getIntent().getBooleanExtra("isFollow", false);
            if(isFollow){
                concern.setBackgroundResource(R.drawable.b_seller_cancel_selector);
            }else {
                concern.setVisibility(View.GONE);
            }
        }
		new BusinessTask().execute(businessInfo.getId());
		new BitmapTask().execute(businessInfo.getLogo());
	}

	@Override
	public void onClick(View v) {
		if (v == signin) {
			Business.instance.switchTab("signin");
		} else if (v == checkMap) {
			checkMap(businessInfo.getAddress().getLatitude(), businessInfo
					.getAddress().getLongitude());
		} else if (v == call) {
			if (businessInfo.getPhone() == null
					|| businessInfo.getPhone().length() == 0) {
				UiUtils.showToast(this, "该商家暂未提供电话");
			} else {
				call(businessInfo.getPhone());
			}
		} else if (v == concern) {
			if (mooerApp.isLoggedin()) {
				if (!concerning) {
					concerning = true;
					concern.setBackgroundResource(R.drawable.b_seller_attention_in);
					new ConcernTask().execute(mooerApp.getUser().getId(),
							businessInfo.getId());
				} else {
					UiUtils.showToast(this, "正在发送关注请求，请稍候再试");
				}
			} else {
				Intent intent = new Intent(this, MoreAccountSetting.class);
				intent.putExtra("isFinish", true);
				startActivityForResult(intent, 0);
			}
		}

	}

	private void call(String phone) {
		if (phone != null && !"".equals(phone.trim())) {
			Uri uri = Uri.parse("tel:" + phone);
			Intent it = new Intent(Intent.ACTION_DIAL, uri);
			startActivity(it);
		}
	}

	private void checkMap(double latitude, double longitude) {
		if (latitude != 0 && longitude != 0) {
			try {
				String mapUri = "geo:" + latitude + "," + longitude;
				Log.i(TAG, mapUri);
				Uri uri = Uri.parse(mapUri);
				Intent it = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(it);

			} catch (Exception e) {
				Log.v(TAG, e.getMessage());
				Uri uri = Uri
						.parse("http://ditu.google.cn/maps?hl=zh&mrt=loc&q="
								+ latitude + "," + longitude);
				try {
					Intent it = new Intent(Intent.ACTION_VIEW, uri);
					startActivity(it);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
	}

	private class BusinessTask extends AsyncTask<Integer, String, Shop> {

		@Override
		protected Shop doInBackground(Integer... params) {
			try {
				mooerApp.getDbHelper().save(businessInfo);
				Shop shop = HttpUtils.fetchShopDetail(params[0]);
				if (shop != null) {
					shop.setAvgConsumption(businessInfo.getAvgConsumption());
					shop.setRating(businessInfo.getRating());
                    if(mooerApp.isLoggedin()){
                        isConcerning = HttpUtils.checkFollowShop(mooerApp.getUser().getId(), shop.getId());
                    }
				}
				return shop;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Shop shop) {
			super.onPostExecute(shop);
			if (shop != null) {
                promotionView.setVisibility(View.GONE);
                couponView.setVisibility(View.GONE);
                concern.setVisibility(View.VISIBLE);
				BusinessInfo.this.businessInfo = shop;
				star.setBackgroundDrawable(UiUtils.selectStar(getResources(),
						businessInfo.getRating()));
				phone.setText("电话：" + businessInfo.getPhone());
				address.setText("地址：" + businessInfo.getAddress().getAddress1());
				concernNumber = shop.getConcernNum();
				concernNum.setText(getString(R.string.concern_num,
						concernNumber));
                if(isConcerning){
                   concern.setBackgroundResource(R.drawable.b_seller_cancel_selector);
                }else {
                   concern.setBackgroundResource(R.drawable.b_seller_attention_selector);
                }
				if (businessInfo.getCoupons().size() > 0) {
					BusinessCouponAdapter couponAdapter = new BusinessCouponAdapter(
							BusinessInfo.this, businessInfo.getCoupons(),
							mooerApp);
					couponView.setAdapter(couponAdapter);
				}
				UiUtils.setListViewHeightBasedOnChildren(couponView);
				if (businessInfo.getPromotions().size() > 0) {
					BusinessPromotionAdapter promotionAdapter = new BusinessPromotionAdapter(
							BusinessInfo.this, businessInfo.getPromotions(),
							mooerApp);
					promotionView.setAdapter(promotionAdapter);
				}
				UiUtils.setListViewHeightBasedOnChildren(promotionView);
				if (infoScroll != null) {
					infoScroll.post(new Runnable() {
						@Override
						public void run() {
							infoScroll.scrollTo(0, icon.getScrollY());
                            promotionView.setVisibility(View.VISIBLE);
                            couponView.setVisibility(View.VISIBLE);
						}
					});
				}
			}
		}

	}

	private class ConcernTask extends AsyncTask<Integer, Integer, String> {

		private boolean isException;

		@Override
		protected String doInBackground(Integer... arg0) {
            int count = 0;
			try {
                if(isConcerning){
				   count = HttpUtils.cancelFollowShop(arg0[0], arg0[1]);
                } else {
                   count = HttpUtils.doFollowShop(arg0[0], arg0[1]);
                }
			} catch (Exception e) {
				isException = true;
				Log.e(TAG, "", e);
			}
			return String.valueOf(count);
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
            if (isException) {
                if (isConcerning) {
                    concern.setBackgroundResource(R.drawable.b_seller_cancel_selector);
                    UiUtils.showToast(BusinessInfo.this, "取消关注失败");
                } else {
                    concern.setBackgroundResource(R.drawable.b_seller_attention_selector);
                    UiUtils.showToast(BusinessInfo.this, "关注失败");
                }
            } else {
                if (isConcerning) {
                    isConcerning = false;
                    concern.setBackgroundResource(R.drawable.b_seller_attention_selector);
                    UiUtils.showToast(BusinessInfo.this, "取消关注成功");
                    concernNum.setText(getString(R.string.concern_num,
                            result));
                } else {
                    isConcerning = true;
                    concern.setBackgroundResource(R.drawable.b_seller_cancel_selector);
                    UiUtils.showToast(BusinessInfo.this, "关注成功");
                    concernNum.setText(getString(R.string.concern_num,
                            result));
                }
            }
			concerning = false;
		}

	}

	private class BitmapTask extends AsyncTask<String, Integer, Bitmap> {

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			bitmap = HttpUtils.downloadBitmap(params[0]);
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			if (result != null) {
				icon.setImageBitmap(result);
			}
		}

	}

}
